package MybatisDemo;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.SQLException;

public class Configs
{
	private String url;
	private String username;
	private String password;
	private String driver;
	private String MappingClassName;

	public String getMappingClassName()
	{
		return MappingClassName;
	}

	//c3p0数据连接池对象
	ComboPooledDataSource ds;

	public void read() throws FileNotFoundException, DocumentException
	{
		SAXReader saxReader = new SAXReader();
		saxReader.setEncoding("UTF-8");

		//读取配置文件
		Document read = saxReader.read(new FileInputStream("configus.xml"));
		Element root = read.getRootElement();
		Node dataSource = root.selectSingleNode("dataSource");
		Element dataSource_ele = (Element) dataSource;
		//读取创建连接池属性
		for (Element e : dataSource_ele.elements())
		{
			String name = e.attributeValue("name");
			String value = e.attributeValue("value");
			switch (name)
			{
				case "url":
					this.url = value;
					break;
				case "username":
					this.username = value;
					break;
				case "password":
					this.password = value;
					break;
				case "driver":
					this.driver = value;
					break;
			}
		}
		//读取映射数据库的pojo类接口
		MappingClassName = ((Element) root.selectSingleNode("//mappers")).element("package").attributeValue("name");
		System.out.println(MappingClassName);
	}

	void CreateDataSource() throws PropertyVetoException
	{
		ds = new ComboPooledDataSource();
		ds.setJdbcUrl(url);
		ds.setUser(username);
		ds.setPassword(password);
		ds.setDriverClass(driver);
	}

	//获取一个连接对象
	Connection getconnection() throws SQLException
	{
		return ds.getConnection();
	}

	void print()
	{
		System.out.println("url: " + url);
		System.out.println("name: " + username);
		System.out.println("password: " + password);
		System.out.println("driver: " + driver);
	}

	@Test
	public void test() throws PropertyVetoException, DocumentException, FileNotFoundException
	{
		read();
	}
}
